//
//  StoreIdCardViewController.m
//  renmingongshe
//
//  Created by macbook on 2017/11/8.
//  Copyright © 2017年 xiaodian. All rights reserved.
//

#import "StoreIdCardViewController.h"
#import "THWAlertControler.h"
#import "SelectOnePicture.h"
#import "StoreIdViewController.h"
@interface StoreIdCardViewController ()

{
    NSData *_zhengData;
    NSData *_fanData;
    
    NSMutableDictionary *_mupara;
    BOOL haveUpload;
}
@property (weak, nonatomic) IBOutlet UIButton *TopBtn;
@property (weak, nonatomic) IBOutlet UIButton *BottomBtn;
@property (strong, nonatomic) SelectOnePicture *OnePicture;
@end

@implementation StoreIdCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.titleLabel.text = @"身份证照";
    
    _mupara = [[NSMutableDictionary alloc]initWithDictionary:_para];
    
    _TopBtn.layer.borderColor = [[UIColor redColor]CGColor];
    _TopBtn.layer.borderWidth = 1.0f;
    _TopBtn.layer.masksToBounds = YES;
    if ([_para[@"shopType"]integerValue]) {
        _BottomBtn.hidden = YES;
    }
}

- (IBAction)zhengClick:(UIButton *)sender {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {  // 没权限，提醒用户开启权限
        THWAlertControler *qq = [[THWAlertControler alloc]init];
        UIAlertController *alert = [qq alertmessage:@"请先允许店猫访问你的相册及相机功能，前往设置？" Title:nil andBlock:^{
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            [[UIApplication sharedApplication] openURL:url];
        }];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    // 调用相册
    if (!_OnePicture) {
        _OnePicture = [[SelectOnePicture alloc]initWithFrame:CGRectZero];
        _OnePicture.ratioOfWidthAndHeight =  600/380.0;
        _OnePicture.enableCutImg  =YES;
        _OnePicture.superController = self;
    }
    // 点击相册的回调
    [_OnePicture toSelectImage:^(NSData *imageData) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"post_disappear"  object:nil];
        //        NSString *tempstr = API(MineShopIma);
        //        [weakSelf imageUpload:imageData withUrl:tempstr];
        [sender setBackgroundImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal];
        _zhengData = imageData;
    }];
}
- (IBAction)fanClick:(UIButton *)sender {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {  // 没权限，提醒用户开启权限
        THWAlertControler *qq = [[THWAlertControler alloc]init];
        UIAlertController *alert = [qq alertmessage:@"请先允许店猫访问你的相册及相机功能，前往设置？" Title:nil andBlock:^{
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            [[UIApplication sharedApplication] openURL:url];
        }];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    // 调用相册
    if (!_OnePicture) {
        _OnePicture = [[SelectOnePicture alloc]initWithFrame:CGRectZero];
        _OnePicture.ratioOfWidthAndHeight = 600/380.0;
        _OnePicture.enableCutImg  =YES;
        _OnePicture.superController = self;
    }
    // 点击相册的回调
    [_OnePicture toSelectImage:^(NSData *imageData) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"post_disappear"  object:nil];
        //        NSString *tempstr = API(MineShopIma);
        //        [weakSelf imageUpload:imageData withUrl:tempstr];
        [sender setBackgroundImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal];
        _fanData = imageData;
    }];
}
- (IBAction)uploadClick:(UIButton *)sender {
    if (!_zhengData||!_fanData) {
        [self.view Message:@"请上传图片"];
        return;
    }
    NSMutableArray *arr = [NSMutableArray array];
    [self imageUpload:_zhengData withUrl:API(MineShopIma) suc:^(id responseObject){
        [arr addObject:responseObject[@"msg"]];
        [self imageUpload:_fanData withUrl:API(MineShopIma) suc:^(id responseObject){
            [self.view Message:@"上传成功"];
            [arr addObject:responseObject[@"msg"]];
            haveUpload = YES;
            [_mupara setObject:[arr componentsJoinedByString:@","] forKey:@"card_img"];
            if ([_para[@"shopType"]integerValue]) {
                //企业
                StoreIdViewController *vc = [[StoreIdViewController alloc]init];
                vc.para = _mupara;
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                //个人
            }
            
        }];
    }];
}
- (IBAction)submitClick:(id)sender {
    if (!haveUpload) {
        [self.view Message:@"请上传图片"];
        return;
    }
    [THWManager PostHttp:API(MineStoreFillClick) Parameters:_mupara Success:^(id responseObject) {
        [self.view Message:responseObject[@"msg"]];
        if ([responseObject[@"status"]integerValue]==1) {
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                [self.navigationController popToRootViewControllerAnimated:YES];
            });
        }
        
    } andFalse:^(NSError *error) {
        
    }];
}
- (void)imageUpload:(NSData*)data withUrl:(NSString *)url suc:(void(^)(id))suc
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
    NSDictionary *dic = @{@"name":@"upload_file",@"type":@"image/png",@"tmp_name":fileName,@"size":@(data.length)};
    NSDictionary *para = @{@"flag":@"4",@"upload_file":@[dic], @"userToken":[Utils getUserToken]};
    [self.view loadingOnAnyView];
    [THWManager PostImageWithData:url imageData:data otherParamters:para success:^(NSURLSessionDataTask *task, id responseObject) {
        [self.view removeAnyView];
        
        suc(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [self.view removeAnyView];
        [self.view Message:@"请重新上传"];
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
